import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Space } from 'antd';
import { UserOutlined, LockOutlined, LoginOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import './Login.css';

const { Title, Text } = Typography;

interface LoginFormData {
  employeeId: string;
  password: string;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();

  // 从location state中获取用户原来想访问的页面
  const from = (location.state as any)?.from?.pathname || '/dashboard';

  const handleLogin = async (values: LoginFormData) => {
    setLoading(true);
    
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          employeeId: values.employeeId,
          password: values.password,
        }),
      });

      const result = await response.json();

      if (result.success) {
        // 存储token和用户信息
        localStorage.setItem('token', result.data.token);
        localStorage.setItem('userInfo', JSON.stringify(result.data.userInfo));
        
        message.success('登录成功！');
        
        // 跳转到用户原来想访问的页面，或者首页
        navigate(from, { replace: true });
      } else {
        message.error(result.message || '登录失败');
      }
    } catch (error) {
      console.error('登录异常:', error);
      message.error('登录服务异常，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 预填密码
  const handleEmployeeIdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const employeeId = e.target.value.toUpperCase(); // 转换为大写
    
    // 如果工号是6位数字，自动填充密码
    if (/^\d{6}$/.test(employeeId)) {
      form.setFieldsValue({ password: '000000' });
    }
    // 如果工号是K开头+7位数字格式，自动填充密码
    else if (/^K\d{7}$/.test(employeeId)) {
      form.setFieldsValue({ password: '000000' });
    }
    
    // 更新表单中的工号值为大写
    form.setFieldsValue({ employeeId: employeeId });
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <div className="login-header">
          <div className="login-logo">
            <div className="logo-icon">
              <LoginOutlined />
            </div>
            <Title level={2} className="logo-title">SQLCheck</Title>
          </div>
          <Text type="secondary" className="login-subtitle">
            SQL兼容性检查平台
          </Text>
        </div>

        <Card className="login-card" bordered={false}>
          <div className="card-header">
            <Title level={3}>员工登录</Title>
            <Text type="secondary">请输入您的工号进行登录</Text>
          </div>

          <Form
            form={form}
            name="login"
            onFinish={handleLogin}
            autoComplete="off"
            size="large"
            className="login-form"
          >
            <Form.Item
              name="employeeId"
              rules={[
                { required: true, message: '请输入工号' },
                { 
                  pattern: /^(\d{6}|K\d{7})$/i, 
                  message: '工号格式不正确，请输入6位数字工号或K开头+7位数字工号（如K0011111））' 
                }
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="请输入工号（如：012345 或 K0011111）"
                maxLength={8}
                onChange={handleEmployeeIdChange}
                style={{ textTransform: 'uppercase' }}
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
                autoComplete="current-password"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                block
                className="login-button"
              >
                {loading ? '登录中...' : '登录'}
              </Button>
            </Form.Item>
          </Form>

          <div className="login-tips">
            <Space direction="vertical" size="small">
              <Text type="secondary" className="tip-text">
                • 支持两种工号格式：6位数字工号（如：012345）或K开头+7位数字工号（如：K0011111）
              </Text>
              <Text type="secondary" className="tip-text">
                • 直接登录即可，无需注册
              </Text>
              <Text type="secondary" className="tip-text">
                • 默认密码为：000000
              </Text>
              <Text type="secondary" className="tip-text">
                • 如有问题请联系系统管理员秦晓012950、黄如春015271
              </Text>
            </Space>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Login;